//
//  PreviewViewController.swift
//  Reader
//
//  Created by wang shuguan on 5/21/21.
//

import UIKit
import MagicalRecord
import SwiftyJSON
class PreviewViewController: UIViewController {
    @IBOutlet weak var contentLabel: UILabel!
    var datas:[String] = []
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        changeTopConstraint()
        contentLabel.text = datas.first
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .save, target: self, action: #selector(save))
    }


    @objc func save() {
        let nId = ((BookModel.findAll() ?? []).toJSON().map({$0["id"].intValue}).max() ?? 0)+1
        UIScreen.startAnimation()
        MagicalRecord.save(blockAndWait: {[weak self](context) in
            if let SSelf = self{
                _ = BookModel.create(json: JSON(["id":nId,"name":SSelf.title ?? "","url":""]), inContext: context)
                let numberFormatter = NumberFormatter()
                /// 如果不设置locle 跟随系统语言
                numberFormatter.locale = Locale(identifier: "zh_CN")
                numberFormatter.numberStyle = NumberFormatter.Style.spellOut
                for i in 0..<SSelf.datas.count {
                    let data = SSelf.datas[i]
                    let title = numberFormatter.string(from: NSNumber(value: i+1)) ?? ""
                    _ = ChapterModel.createOrReplace(jsons: [JSON(["bid":nId,"id":i,"text":data,"title":"第\(title)页","url":""])], inContext: context)
                }
                (ReadModel.models(bid: "\(nId)", in: context) as [NSManagedObject]).removeAllModels(inContext: context)
                DispatchQueue.main.after(0.3) {
                    UIScreen.stopAnimation()
                    self?.navigationController?.popVC()
                }
            }
        })
    }
}
